from tools import tools
from gm.api import *
import pandas as pd
import numpy as np
from sklearn import preprocessing


def 成长模型(index, now):
    symbol_list = tools.get_symbol_list(index, now)

    last_day = get_previous_trading_date('SHSE', now)
    day_time = last_day
    # symbol_list=tools.read_MSCI()
    df = pd.DataFrame([])
    df['symbol'] = symbol_list
    df['EBITG'] = -999
    df['NPG'] = -999
    df['TAG'] = -999  # MPG取不到，用TAG代替
    df['GPG'] = -999
    df['OPG'] = -999
    df['OCG'] = -999
    # df[''] = -999
    # 求出EBITG
    for number in range(len(symbol_list)):
        try:
            _df = get_fundamentals_n(table='deriv_finance_indicator', symbols=symbol_list[number], end_date=day_time,
                                     count=2, fields="EBITMARGIN")
            now_EBITMARGIN = _df[0]['EBITMARGIN']
            last_EBITMARGIN = _df[1]['EBITMARGIN']
            EBITG = ((now_EBITMARGIN - last_EBITMARGIN) / last_EBITMARGIN)

            df.iloc[number, 1] = EBITG
        except:
            df.iloc[number, 1] = -999

    # 求NPG
    _df = get_fundamentals(table='deriv_finance_indicator', symbols=symbol_list, start_date=day_time, end_date=day_time,
                           fields="NPGRT", df=True)
    if len(_df) == len(symbol_list):
        df['NPG'] = _df['NPGRT']
    else:
        for number in range(len(symbol_list)):
            try:
                _df = get_fundamentals(table='deriv_finance_indicator', symbols=symbol_list[number],
                                       start_date=day_time, end_date=day_time, fields='NPGRT')
                _NPG = tools.get_data_value(_df, 'NPGRT')

                df.iloc[number, 2] = _NPG[0]
            except:
                df.iloc[number, 2] = -999

    # 求出TAG
    _df = get_fundamentals(table='deriv_finance_indicator', symbols=symbol_list, start_date=day_time,
                           end_date=day_time, fields="TAGRT", df=True)
    if len(_df) == len(symbol_list):
        df['TAG'] = _df['TAGRT']
    else:
        for number in range(len(symbol_list)):
            try:
                _df = get_fundamentals(table='deriv_finance_indicator', symbols=symbol_list[number],
                                       start_date=day_time, end_date=day_time, fields='TAGRT')
                _NPG = tools.get_data_value(_df, "TAGRT")
                df.iloc[number, 2] = _NPG[0]
            except:
                df.iloc[number, 2] = -999

    # 求GPG
    for number in range(len(symbol_list)):
        try:
            _df = get_fundamentals_n(table='deriv_finance_indicator', symbols=symbol_list[number], end_date=day_time,
                                     count=2, fields="OPGPMARGIN")
            now_EBITMARGIN = _df[0]['OPGPMARGIN']
            last_EBITMARGIN = _df[1]['OPGPMARGIN']
            EBITG = ((now_EBITMARGIN - last_EBITMARGIN) / last_EBITMARGIN)

            df.iloc[number, 4] = EBITG
        except:
            df.iloc[number, 4] = -999

    df = df.dropna()
    df_factor = df.iloc[:, 1:]
    df_factor = np.asmatrix(df_factor)

    # 先进行列归一化，然后对每行进行标准化处理
    df_factor = preprocessing.MinMaxScaler().fit_transform(df_factor)
    weight = [[-1], [-1], [-1], [-1], [-1], [-1]]
    weight_mat = np.asmatrix(weight)
    res = np.dot(df_factor, weight_mat)
    df["score"] = (res)

    df = (df.sort_values(['score']))
    print(df)
    symbol_list = []
    for _ in df['symbol'].values:
        symbol_list.append(_)

    return symbol_list
